import * as turf from "@turf/turf";
import Style from "ol/style/Style";
import Text from "ol/style/Text";
import Fill from "ol/style/Fill";
import Stroke from "ol/style/Stroke";
import LineString from "ol/geom/LineString";

export function showMeasurements(feature) {
  const styles = [];
  if (feature.getGeometry().getType() === "Circle") {
    const extent = feature.getGeometry().getExtent();
    const center = feature.getGeometry().getCenter();
    const line = new LineString([
      [extent[0], extent[1]],
      [extent[2], extent[1]],
    ]);
    line.transform("EPSG:3857", "EPSG:4326");
    const distance =
      (
        turf.pointToLineDistance(
          turf.toWgs84(turf.point(center)),
          turf.lineString(line.getCoordinates())
        ) *
        1000 *
        2 *
        1000
      ).toFixed(0) + "mm";

    return [
      new Style({
        text: new Text({
          font:
            feature.getId() && feature.getId().indexOf("GK") > 0
              ? "6px Calibri,sans-serif"
              : "16px Calibri,sans-serif",
          overflow: true,
          fill: new Fill({
            color: "#000",
          }),
          stroke: new Stroke({
            color: "#fff",
            width: 3,
          }),
          text: distance,
          placement: "line",
        }),
        geometry: new LineString([
          [extent[0], extent[1]],
          [extent[2], extent[1]],
        ]),
      }),
    ];
  }
  const coords = feature.getGeometry().getCoordinates()[0];
  if (
    coords[0][0] === coords[coords.length - 1][0] &&
    coords[0][1] === coords[coords.length - 1][1]
  ) {
    for (let i = 0; i < coords.length - 1; i++) {
      const distance =
        (
          turf.distance(
            turf.toWgs84(turf.point(coords[i])),
            turf.toWgs84(turf.point(coords[i + 1]))
          ) *
          1000 *
          1000
        ).toFixed(0) + "mm";

      styles.push(
        new Style({
          text: new Text({
            font:
              feature.getId() && feature.getId().indexOf("GK") > 0
                ? "6px Calibri,sans-serif"
                : "16px Calibri,sans-serif",
            fill: new Fill({
              color: "#000",
            }),
            stroke: new Stroke({
              color: "#fff",
              width: 3,
            }),
            text: distance,
            placement: "line",
          }),
          geometry: new LineString([coords[i], coords[i + 1]]),
        })
      );
    }
  }

  return styles;
}

// WEBPACK FOOTER //
// ./src/components/pmEditor/measure.js
